package ru.ifmo.ctddev.larionov.task9;

import java.io.*;
import java.net.*;
import java.util.*;

public class HelloUDPClient {

	private byte[] address;
	private int port;
	private String name;
	private Random rand = new Random();
	Thread[] threads = new Thread[100];

	public HelloUDPClient(byte[] add, int p, String n) {
		address = add.clone();
		port = p;
		name = n;
		for (int i = 0; i < 1; ++i) {
			threads[i] = new Thread(new Runnable() {
				@Override
				public void run() {
					InetAddress iAdd;
					try {
						iAdd = InetAddress.getByAddress(address);
						DatagramSocket out;
						DatagramSocket in;
						try {
							out = new DatagramSocket();
							int inPort = rand.nextInt(55000) + 10000;
							in = new DatagramSocket(inPort);
							out.connect(iAdd, port);
							byte[] buf = { (byte) (inPort / 100),
									(byte) (inPort % 100) };
							DatagramPacket dPacket = new DatagramPacket(buf,
									buf.length);
							out.send(dPacket);
							in.receive(dPacket);
							out.connect(iAdd, dPacket.getData()[0] * 100
									+ dPacket.getData()[1]);
							for (int i = 1; i <= 10; ++i) {
								String tmp = name + " "
										+ Thread.currentThread().getName()
										+ "_" + i;
								buf = tmp.getBytes();
								dPacket = new DatagramPacket(buf, buf.length);
								out.send(dPacket);

							}
						} catch (SocketException e) {
							System.err.println("Error with socket!");
						} catch (IOException e) {
							System.err.println("OH SHI~");
						}
					} catch (UnknownHostException e) {
						System.err.println("Unknown host!");
					}
				}
			}, "" + i);
			threads[i].start();
		}
	}
}
